Telegram Group & Telegram Channel
🐍 7 “бесполезных” функций Python, которые на самом деле полезны

Инструменты из стандартной библиотеки, которые могут удивить:

1. textwrap.dedent() — убирает отступы у многострочного текста.

import textwrap
text = textwrap.dedent(\"\"\"
Привет!
Это текст с отступами.
\"\"\").strip()
print(text)

2. difflib.get_close_matches() — находит схожие строки.

import difflib
words = ["python", "java", "javascript"]
print(difflib.get_close_matches("javascrip", words))

3. uuid.uuid4() — создает уникальный идентификатор.

import uuid
print(uuid.uuid4())

4. shutil.get_terminal_size() — определяет размеры терминала.

import shutil
columns, rows = shutil.get_terminal_size()
print(f"Размер терминала: {columns}x{rows}")

5. functools.lru_cache() — сохраняет результаты функции в кэше.

from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
print(fib(100))

6. itertools.groupby() — группирует элементы по ключу.

from itertools import groupby
data = [(&apos;fruit&apos;, &apos;apple&apos;), (&apos;fruit&apos;, &apos;banana&apos;), (&apos;veg&apos;, &apos;carrot&apos;)]
for key, group in groupby(data, lambda x: x[0]):
print(key, list(group))

7. contextlib.suppress() — элегантная альтернатива конструкции try-except.

from contextlib import suppress
with suppress(FileNotFoundError):
open("not_exist.txt")

@Python_Community_ru



tg-me.com/Python_Community_ru/2569
Create:
Last Update:

🐍 7 “бесполезных” функций Python, которые на самом деле полезны

Инструменты из стандартной библиотеки, которые могут удивить:

1. textwrap.dedent() — убирает отступы у многострочного текста.

import textwrap
text = textwrap.dedent(\"\"\"
Привет!
Это текст с отступами.
\"\"\").strip()
print(text)

2. difflib.get_close_matches() — находит схожие строки.

import difflib
words = ["python", "java", "javascript"]
print(difflib.get_close_matches("javascrip", words))

3. uuid.uuid4() — создает уникальный идентификатор.

import uuid
print(uuid.uuid4())

4. shutil.get_terminal_size() — определяет размеры терминала.

import shutil
columns, rows = shutil.get_terminal_size()
print(f"Размер терминала: {columns}x{rows}")

5. functools.lru_cache() — сохраняет результаты функции в кэше.

from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
print(fib(100))

6. itertools.groupby() — группирует элементы по ключу.

from itertools import groupby
data = [(&apos;fruit&apos;, &apos;apple&apos;), (&apos;fruit&apos;, &apos;banana&apos;), (&apos;veg&apos;, &apos;carrot&apos;)]
for key, group in groupby(data, lambda x: x[0]):
print(key, list(group))

7. contextlib.suppress() — элегантная альтернатива конструкции try-except.

from contextlib import suppress
with suppress(FileNotFoundError):
open("not_exist.txt")

@Python_Community_ru

BY Python Community


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/Python_Community_ru/2569

View MORE
Open in Telegram


Python Community Telegram | DID YOU KNOW?

Date: |

Telegram is riding high, adding tens of million of users this year. Now the bill is coming due.Telegram is one of the few significant social-media challengers to Facebook Inc., FB -1.90% on a trajectory toward one billion users active each month by the end of 2022, up from roughly 550 million today.

How to Buy Bitcoin?

Most people buy Bitcoin via exchanges, such as Coinbase. Exchanges allow you to buy, sell and hold cryptocurrency, and setting up an account is similar to opening a brokerage account—you’ll need to verify your identity and provide some kind of funding source, such as a bank account or debit card. Major exchanges include Coinbase, Kraken, and Gemini. You can also buy Bitcoin at a broker like Robinhood. Regardless of where you buy your Bitcoin, you’ll need a digital wallet in which to store it. This might be what’s called a hot wallet or a cold wallet. A hot wallet (also called an online wallet) is stored by an exchange or a provider in the cloud. Providers of online wallets include Exodus, Electrum and Mycelium. A cold wallet (or mobile wallet) is an offline device used to store Bitcoin and is not connected to the Internet. Some mobile wallet options include Trezor and Ledger.

Python Community from it


Telegram Python Community
FROM USA